const MBTI = require('../../utils/mbti-questions.js');
const SDS = require('../../utils/sds-questions.js');
const { request } = require('../../utils/api.js');

const PAGE_SIZE = 3;

Page({
  data: {
    type: '',
    testTitle: '',
    testDesc: '',
    questions: [],
    answers: [],
    pageStart: 0,
    currentPage: 1,
    totalPages: 1,
    currentQuestions: [],
    optionText: {
      1: "没有或很少时间",
      2: "小部分时间", 
      3: "相当多时间",
      4: "绝大部分或全部时间"
    },
    // 弹窗相关数据
    showResultModal: false,
    resultData: {
      title: '',
      scoreText: '',
      levelText: '',
      interpretation: ''
    }
  },

  onLoad(options) {
    const type = options.type;
    console.log('测评类型:', type);
    
    let questions = [];
    let title = '', desc = '';
    
    if (type === 'mbti') {
      questions = MBTI.questions;
      title = MBTI.title;
      desc = MBTI.description;
    } else if (type === 'sds') {
      questions = SDS;
      title = 'SDS 抑郁自评量表';
      desc = '我们理解每个人都会有情绪起伏的时刻。这份量表将帮助您梳理近期的心理状态，共20个简单问题，请根据过去一周内最符合您真实感受的选项作答。您的声音很重要，我们始终在这里提供支持。';
    }
    
    console.log('题目数量:', questions.length);
    
    const totalPages = Math.ceil(questions.length / PAGE_SIZE);
    const currentQuestions = questions.slice(0, PAGE_SIZE);
    
    this.setData({
      type,
      testTitle: title,
      testDesc: desc,
      questions,
      answers: Array(questions.length).fill(''),
      totalPages,
      currentQuestions
    });
  },

  // 更新当前页题目
  updateCurrentQuestions() {
    const start = this.data.pageStart;
    const end = Math.min(start + PAGE_SIZE, this.data.questions.length);
    const currentQuestions = this.data.questions.slice(start, end);
    this.setData({ currentQuestions });
  },

  selectOption(e) {
    const qIndex = e.currentTarget.dataset.qindex;
    const value = e.currentTarget.dataset.value;
    const answers = this.data.answers.slice();
    answers[qIndex] = value;
    this.setData({ answers });
    
    console.log(`选择第${qIndex + 1}题答案:`, value);
  },

  prevPage() {
    if (this.data.currentPage > 1) {
      const currentPage = this.data.currentPage - 1;
      const pageStart = (currentPage - 1) * PAGE_SIZE;
      this.setData({ currentPage, pageStart });
      this.updateCurrentQuestions();
    }
  },

  nextPage() {
    // 校验本页是否全部作答
    const pageStart = this.data.pageStart;
    const pageEnd = Math.min(pageStart + PAGE_SIZE, this.data.questions.length);
    
    for (let i = pageStart; i < pageEnd; i++) {
      if (!this.data.answers[i]) {
        wx.showToast({ 
          title: '请完成本页所有题目', 
          icon: 'none' 
        });
        return;
      }
    }
    
    if (this.data.currentPage < this.data.totalPages) {
      const currentPage = this.data.currentPage + 1;
      const pageStart = (currentPage - 1) * PAGE_SIZE;
      this.setData({ currentPage, pageStart });
      this.updateCurrentQuestions();
    }
  },

  submitTest() {
    // 检查 token
    const token = wx.getStorageSync('access_token');
    if (!token) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      return;
    }
  
    // 校验所有题目
    let hasEmpty = false;
    for (let i = 0; i < this.data.answers.length; i++) {
      if (!this.data.answers[i]) {
        hasEmpty = true;
        break;
      }
    }
    if (hasEmpty) {
      wx.showToast({ title: '请完成所有题目', icon: 'none' });
      return;
    }
  
    // 构造答案对象
    let answersObj = {};
    if (this.data.type === 'mbti') {
      this.data.answers.forEach((v, i) => {
        answersObj[i + 1] = v;
      });
    } else if (this.data.type === 'sds') {
      this.data.answers.forEach((v, i) => {
        const answer = parseInt(v);
        if (answer >= 1 && answer <= 4) {
          answersObj[i + 1] = answer;
        } else {
          wx.showToast({ title: `第${i + 1}题答案无效`, icon: 'none' });
          return;
        }
      });
    }
  
    let url = this.data.type === 'mbti' ? '/api/test/mbti' : '/api/test/sds';
  
    console.log('开始提交，显示加载中...');
    wx.showLoading({ title: '提交中...' });
  
    request({
      url,
      method: 'POST',
      data: { answers: answersObj }
    }).then(res => {
      console.log('请求成功，准备隐藏加载中...');
      wx.hideLoading();
      console.log('提交响应:', res);
  
      if (res.code === 200) {
        // 处理测试结果并显示弹窗
        const resultData = this.processResultData(res.data);
        console.log('处理后的结果数据:', resultData);
        
        this.setData({
          showResultModal: true,
          resultData: resultData
        });
        
        console.log('弹窗已显示');
      } else {
        wx.showToast({ title: res.msg || '提交失败', icon: 'none' });
      }
    }).catch(err => {
      console.log('请求失败，隐藏加载中...');
      wx.hideLoading();
      console.error('提交错误:', err);
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  },

  // 处理结果数据
  processResultData(data) {
    const type = this.data.type;
    console.log('处理结果数据，类型:', type, '数据:', data);
    
    let resultData = {
      title: '',
      scoreText: '',
      levelText: '',
      interpretation: ''
    };

    if (type === 'mbti') {
      resultData = {
        title: 'MBTI 测试结果',
        scoreText: '你的类型：' + (data.mbti_type || ''),
        levelText: '',
        interpretation: data.description || ''
      };
    } else if (type === 'sds') {
      resultData = {
        title: 'SDS 测试结果',
        scoreText: '你的标准分：' + (data.standard_score || ''),
        levelText: (data.depression_level || '') + '：',
        interpretation: data.interpretation || ''
      };
    }

    console.log('处理后的结果:', resultData);
    return resultData;
  },

  // 关闭结果弹窗
  closeResultModal() {
    this.setData({
      showResultModal: false
    });
    // 确保加载提示被隐藏
    wx.hideLoading();
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 完成按钮点击事件
  onFinish() {
    this.setData({
      showResultModal: false
    });
    
    // 确保加载提示被隐藏
    wx.hideLoading();
    
    // 跳转到首页
    wx.switchTab({
      url: '/pages/test-list/test-list'
    });
  },

  // 手动隐藏加载提示（调试用）
  hideLoadingManually() {
    console.log('手动隐藏加载中...');
    wx.hideLoading();
    wx.showToast({ title: '已手动隐藏加载', icon: 'none' });
  }
});